import { Component, Input, Output, EventEmitter, OnInit, OnChanges } from '@angular/core';
import { NzNotificationService } from 'ng-zorro-antd';
import { Router } from '@angular/router';
import { HttpServcie } from '../../../../service/http.service';
import { Config } from '../../../../service/config';
import { el } from "@angular/platform-browser/testing/src/browser_util";
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { InformationBean } from '../bean/information.bean';
import * as moment from 'moment';
import {FileUploader,FileItem,ParsedResponseHeaders} from  'ng2-file-upload';

@Component({
    selector: 'information-add',
    templateUrl: 'information-add.html',
    styleUrls: ['information-add.scss']
})

export class InformationAddPage implements OnInit, OnChanges {
    validateForm: FormGroup;
    isSpinning: boolean = false;
    showImage: any = [];
    config=Config;
     fileUploader = new FileUploader({
        url: Config.IP+Config.API.upload,
        method: "POST",
        itemAlias: "file",
        autoUpload: false,
        headers:[
            {name:"Authorization",value:'Bearer ' + window.localStorage['token']}
        ]
    });
    @Input() inValue: any = [];
    @Output("outPut") outPut = new EventEmitter();
    informationBean: InformationBean = new InformationBean();
    constructor(
        private fb: FormBuilder,
        private httpServcie: HttpServcie,
        private _notification: NzNotificationService,
        private router: Router
    ) {
        
    }
    ngOnInit() {
      this.validateForm = this.fb.group({
        title: [null, [Validators.required]],   //标题
        subTitle: [null, [Validators.required]],   //副标题
      });


        this.informationBean.createPartyId = JSON.parse(window.localStorage['user']).partyId;
        this.informationBean.createUserId = JSON.parse(window.localStorage['user']).id;
        this.informationBean.createTime = moment(new Date()).format('YYYYMMDDHHmmss');

    }

    ngOnChanges() {

    }



    //交验
    getFormControl(name) {
        return this.validateForm.controls[name];
    }

    add(){
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
      }
      //处理是否提交
      for (const i in this.validateForm.controls) {
        if(!this.validateForm.controls[i].valid){
          return;
        }
      }

        this.isSpinning = true;
        this.informationBean.content = btoa(encodeURIComponent(this.informationBean.content));;
        this.informationBean.fileUrls = this.showImage.join(',');
        let ob = this.httpServcie.addInformation(this.informationBean);
        ob.subscribe((data)=>{
            this.isSpinning = false;
            if(data.status==200){
                this._notification.create('success', '成功提示', '新增成功');
                this.outPut.emit(data);
            }else if (data.status === 401) {
                this.router.navigateByUrl('/login');
                return;
            }else{
                this._notification.create('error', '错误提示', data.message);
            }
            
        })
    }


    //选择文件后调用的方法
    selectedFileOnChanged(event){
        if(event.target.files[0].type.match()){
            //手动上传的
            this.fileUploader.uploadAll();
            this.fileUploader.onSuccessItem =(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders)=>{
                    if(status==200){
                        //判断是否是图片

                            this.showImage.push(JSON.parse(response).data);
                            //this.userBean.qualificationsUrl = JSON.parse(response).data;

                    }
            }
        }
    }

    delete(param){
        this.httpServcie.deleteUpload(param).subscribe(data=>{
            if(data.status==200){
                this.httpServcie.removeByValue(this.showImage,param);
                //this._notification.create('success', '成功提示', '移除成功');
            }else{
                //this._notification.create('error', '失败提示', data.message);
                return;
            }
        },error=>{

        });
    }
    
}
